package com.timemanager.activity;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.timemanager.R;
import com.timemanager.util.Utility;

public class SetPassword extends AppCompatActivity {

    private EditText oldPassword;

    private EditText newPassword;

    private EditText confirmPassword;

    private LinearLayout oldPasswordLayout;

    private Button btnConfirm;

    private TextView titleText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_password);
        oldPassword = (EditText)findViewById(R.id.old_passwrd);
        newPassword = (EditText) findViewById(R.id.new_passwrd);
        confirmPassword = (EditText)findViewById(R.id.confirm_passwrd);
        oldPasswordLayout = (LinearLayout) findViewById(R.id.old_passwrd_layout);
        btnConfirm = (Button) findViewById(R.id.btn_confirm);
        titleText = (TextView) findViewById(R.id.title_text);
        titleText.setText("设置密码");
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        final String password = prefs.getString("password", "");
        if (password.equals("")) {
            oldPasswordLayout.setVisibility(View.INVISIBLE);
        }
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (password.equals("")) {
                    savePassword();
                } else {
                    oldPasswordLayout.setVisibility(View.VISIBLE);
                    if (oldPassword.getText().toString().equals(password)) {
                        savePassword();
                    } else {
                        Toast.makeText(SetPassword.this, "原密码错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    private void savePassword() {
        if (newPassword.getText().toString().equals(confirmPassword.getText().toString())) {
            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(SetPassword.this).edit();
            editor.putString("password", confirmPassword.getText().toString());
            editor.commit();
            Toast.makeText(SetPassword.this, "设置成功", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            Toast.makeText(SetPassword.this, "两次输入不一致", Toast.LENGTH_SHORT).show();
        }
    }
}
